from .base import BaseAMM
from market import Market


class DPA(BaseAMM):
    def __init__(self, length):
        self.length = length
        self.records = []

    def _price(self, market: Market, records: list, is_true: bool, share: float) -> float:
        base = market.price_records[-1]
        delta = sum(map(lambda x: x["share"], filter(lambda x: x["is_true"] == is_true, records))) * share / 100
        if is_true:
            return base + delta / (len(self.records) + 1)
        else:
            return 1 - (1 - base + delta / (len(self.records) + 1))

    def probability_after_trade(self, market: Market, is_true: bool, share: int) -> float:
        return self._price(market, self.records + [{"is_true": is_true, "share": share}], is_true, share)

    def trade(self, market: Market, is_true: bool, share: float):
        if is_true:
            market.true_share += share
        else:
            market.false_share += share

        self.records.append({"is_true": is_true, "share": share})

        if len(self.records) > self.length:
            self.records.pop(0)

        market.price_records.append(self.price(market))

    def price(self, market: Market) -> float:
        if not len(self.records):
            return 0.5

        is_true = self.records[-1]["is_true"]
        share = self.records[-1]["share"]

        return self._price(market, self.records, is_true, share)

    def probability(self, market: Market) -> float:
        return self.price(market)
